package com.dxysun.mine;


import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.LinkedList;

public class ExifWatermark {

    public static void main(String[] args) throws  Exception {
        LinkedList<Integer> linkedList = new LinkedList<>();
        String inputFilePath = "/Users/dongxiyan/Downloads/pingguo";
        String outputFilePath = "/Users/dongxiyan/Downloads/output";

        File folder = new File(inputFilePath);
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if(!file.getName().endsWith(".jpg")) {
                    continue;
                }

                if (file.isFile()) {
                    System.out.println("文件: " + file.getName() + " done");
                    imgWrite(file, outputFilePath);
                    System.out.println("-------------------------");

                } else if (file.isDirectory()) {
                    System.out.println("目录: " + file.getName());
                }
            }
        }
    }

    public static void imgWrite(File file, String outputFilePath) {
        try {
            String filePath = file.getAbsolutePath();
            Metadata metadata = ImageMetadataReader.readMetadata(file);

            String dateTime = null;
            for (Directory directory : metadata.getDirectories()) {
                for (Tag tag : directory.getTags()) {
                    if (tag.getTagName().equals("Date/Time")) {
                        dateTime = tag.getDescription();
                        System.out.println("dateTime:" + dateTime);
                        break;
                    }
                }
                if (dateTime != null) {
                    break;
                }
            }
            if (dateTime == null) {
                System.out.println(filePath + " dateTime is null");
                return;
            }


            String[] dateTimeParts = dateTime.split(" ");
            if (dateTimeParts.length >= 2) {
                String datePart = dateTimeParts[0];
                String timePart = dateTimeParts[1];

                LocalDate dateInPhoto = LocalDate.parse(datePart, DateTimeFormatter.ofPattern("yyyy:MM:dd"));
                LocalDate dataBirthday = LocalDate.parse("2025-03-07", DateTimeFormatter.ofPattern("yyyy-MM-dd"));

                long daysBetween = Math.abs(ChronoUnit.DAYS.between(dataBirthday, dateInPhoto));
                System.out.println("相差天数: " + Math.abs(daysBetween));
                String[] dateParts = datePart.split(":");
                if (dateParts.length < 3) {
                    System.out.println(filePath + " dateParts is not right");
                    return;
                }
                String formattedDate = dateParts[0] + "-" + dateParts[1] + "-" + dateParts[2] + " " + daysBetween + "天";

                BufferedImage image = ImageIO.read(file);
                BufferedImage watermarkedImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
                Graphics2D g2d = watermarkedImage.createGraphics();
                g2d.drawImage(image, 0, 0, null);

                g2d.setColor(Color.RED);
//                g2d.setFont(new Font("Arial", Font.BOLD, 200));
                File fontFile = new File("/Users/dongxiyan/myFiles/code/1679891232223090.otf");
                Font customFont = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(150f);
                g2d.setFont(customFont);
                g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));

                FontMetrics fontMetrics = g2d.getFontMetrics();
                int x = image.getWidth() - fontMetrics.stringWidth(formattedDate) - 10;
                int y = image.getHeight() - 10;
                g2d.drawString(formattedDate, x, y);

                g2d.dispose();

//              File outputfile = new File("/Users/dongxiyan/Downloads/image1.jpg");
//              ImageIO.write(watermarkedImage, "jpg", outputfile);
                // 获取 JPEG 图像写入器
                Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
                if (!writers.hasNext()) {
                    throw new IllegalStateException("No writers found");
                }
                ImageWriter writer = writers.next();

                // 设置输出
                File outputFile = new File(outputFilePath + "/" + file.getName());
                ImageOutputStream output = ImageIO.createImageOutputStream(outputFile);
                writer.setOutput(output);

                // 设置压缩参数
                ImageWriteParam param = writer.getDefaultWriteParam();
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(1.0f); // 最高质量 (0.0f - 1.0f)

                // 写入图像
                writer.write(null, new IIOImage(watermarkedImage, null, null), param);

                // 清理资源
                output.close();
                writer.dispose();
            }
        } catch (Exception e) {
            System.out.println(file.getAbsolutePath() + " error:" + e.getMessage());
            e.printStackTrace();
        }
    }


}